<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :placeholder="$t('table.name')" v-model="listQuery.name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-select v-model="listQuery.available" :placeholder="$t('table.available')" clearable style="width: 90px" class="filter-item">
        <el-option v-for="(item, index) in availableOptions" :key="index" :label="item.name" :value="item.value" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleMulDelete">{{ $t('table.batch_delete') }}</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
      style="width: 100%;">
      <el-table-column
        type="selection"
        width="35">
      </el-table-column>
      <el-table-column :label="$t('table.id')" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.name')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.curname }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column :label="$t('table.language')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.lang_name }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column :label="$t('table.area')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.area_name }}</span>
        </template>
      </el-table-column> -->
      <el-table-column :label="$t('table.available')" class-name="status-col" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_available | availableFilter">{{ scope.row.available_name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.created_at')" width="160px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.updated_at')" width="160px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updated_at }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button size="mini" type="danger" @click="deleteData(scope.row)">{{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="900px">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="margin-left:50px;">
        <!-- <el-form-item :label="$t('table.area')">
          <el-select v-model="temp.area" class="filter-item" placeholder="Please select">
            <el-option v-for="(item, index) in areaOptions" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item> -->
        <el-form-item :label="$t('table.available')">
          <el-radio v-model="temp.is_available" label="1" name="is_avaliable">{{ $t('table_element.available.on') }}</el-radio>
          <el-radio v-model="temp.is_available" label="0" name="is_avaliable">{{ $t('table_element.available.un') }}</el-radio>
        </el-form-item>
        <template>
          <el-tabs v-model="activeName" >
            <el-tab-pane label="en" name="first">
              <el-form-item :label="$t('table.name')">
                <el-input v-model="temp.name" name="name" />
              </el-form-item>
              <el-form-item :label="$t('table.content')">
                <tinymce :height="300" id="fContent" v-model="temp.content"/>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="zh-cn" name="second">
              <el-form-item :label="$t('table.name')">
                <el-input v-model="temp.cnname" name="cnname" />
              </el-form-item>
              <el-form-item :label="$t('table.content')">
                <tinymce :height="300" id="fCNContent" v-model="temp.cncontent"/>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="zh-hk" name="third">
              <el-form-item :label="$t('table.name')">
                <el-input v-model="temp.hkname" name="hkname" />
              </el-form-item>
              <el-form-item :label="$t('table.content')">
                <tinymce :height="300" id="fHKContent" v-model="temp.hkcontent"/>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="zh-tw" name="fourth">
              <el-form-item :label="$t('table.name')">
                <el-input v-model="temp.twname" name="twname" />
              </el-form-item>
              <el-form-item :label="$t('table.content')">
                <tinymce :height="300" id="fTWContent" v-model="temp.twcontent"/>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchShow, fetchStore, fetchUpdate, fetchDelete, fetchBatchDelete } from '@/api/benefits'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Tinymce from '@/components/Tinymce'
import i18n from '@/lang/index'

export default {
  name: 'Benefit',
  components: { Pagination, Tinymce },
  directives: { waves },
  filters: {
    availableFilter(status) {
      const availableMap = [
        'danger',
        'success'
      ]
      return availableMap[status]
    }
  },
  data() {
    return {
      activeName: 'first',
      isAvailable: 2,
      tableKey: 0,
      list: null,
      content: ``,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        available: 2,
        name: '',
        lang: i18n.locale,
      },
      benefit_ids: [],
      availableOptions: [{ 'value': 2, 'name': i18n.t('table_element.available.all') }, { 'value': 1, 'name': i18n.t('table_element.available.on') }, {'value': 0, 'name': i18n.t('table_element.available.un') }],
      // areaOptions: [{ name : '中国香港', id: 1 }, { name : '中国大陆', id: 2 }],
      showReviewer: false,
      temp: {
        id: '',
        is_available: "1",
        name: '',
        cnname: '',
        hkname: '',
        twname: '',
        content: '',
        cncontent: '',
        hkcontent: '',
        twcontent: '',
        area: 96,
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        name: [{ required: true, message: 'name is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  computed: {
    areaOptions: function () {
        return this.$store.state.locale.areas
    }
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        //console.log(response)
        var data = response.data
        this.list = data.data.data
        this.total = data.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: 'Successful operation',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        is_available: '1',
        name: '',
        cnname: '',
        hkname: '',
        twname: '',
        content: '',
        cncontent: '',
        hkcontent: '',
        twcontent: '',
        area: 96,
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      // 弹窗↓
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        window.tinymce.get('fContent').setContent('')
        window.tinymce.get('fCNContent').setContent('')
        window.tinymce.get('fHKContent').setContent('')
        window.tinymce.get('fTWContent').setContent('')
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          this.temp.lang = i18n.locale
          fetchStore(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Create Success!',
              type: 'success',
              duration: 2000
            })
            this.getList()
            this.$store.dispatch('setAllBenefit').then(res => {})
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.is_available = this.temp.is_available.toString()
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        window.tinymce.get('fContent').setContent(this.temp.content)
        window.tinymce.get('fCNContent').setContent(this.temp.cncontent)
        window.tinymce.get('fHKContent').setContent(this.temp.hkcontent)
        window.tinymce.get('fTWContent').setContent(this.temp.twcontent)
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.lang = i18n.locale
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          fetchUpdate(this.temp.id, tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Success!',
              type: 'success',
              duration: 2000
            })
            this.getList()
            this.$store.dispatch('setAllBenefit').then(res => {})
          })
        }
      })
    },
    handleDelete(row) {
      // console.log(row);
      this.$notify({
        title: 'Success',
        message: 'Delete Success!',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    deleteData(row) {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        fetchDelete(row.id).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'Success',
              message: 'Delete Success!',
              type: 'success',
              duration: 2000
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
            this.$store.dispatch('setAllBenefit').then(res => {})
          }

        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    handleMulDelete() {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        fetchBatchDelete({ benefit_id: this.benefit_ids }).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'Success',
              message: 'Delete Success!',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    handleSelectionChange(val) {
      val.forEach(element => {
        if (this.benefit_ids.indexOf(element.id) == -1) {
          this.benefit_ids.push(element.id)
        }
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
